import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Observable;
import java.util.Observer;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JTextField;


public class InputMessagePanel extends JPanel implements Observer {
	
	private User user;
	private JTextField inputMessage;
	private JButton sendButton;
	private JPanel mainPanel;
	private InputListener inputListener = new InputListener();
	private SimpleDateFormat formattedDate = new SimpleDateFormat("[dd/MM/yy]");
	private SimpleDateFormat formattedTime = new SimpleDateFormat("[hh:mm:ss]");
	
	
	public InputMessagePanel( JPanel mainPanel) {
		super();
		
		user = User.getUser();
		user.addObserver(this);
		
		this.mainPanel = mainPanel;
		mainPanel.add(this);
		setLayout(new BorderLayout());
		
		inputMessage = new JTextField(25);
		inputMessage.addKeyListener( inputListener );
		add(inputMessage, BorderLayout.CENTER);
		
		sendButton = new JButton("Send");
		sendButton.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				inputListener.sendMessage();
			}
		});
		add(sendButton, BorderLayout.EAST);
		
		setBorder( BorderFactory.createTitledBorder( user.getUserName() ));
		
	}
	
	public void addObserver(Observer o){
		inputListener.addObserver(o);
	}
	
	@Override
	public void update(Observable o, Object arg) {
		setBorder( BorderFactory.createTitledBorder( user.getUserName() ) );
	}
	
	
	
	
	
	
	public class MessageInfo{
		
		String message;
		String messageTime;
		String userName;
		

		public MessageInfo( String userName, String message, String messageTime) {
			this.message = message;
			this.messageTime = messageTime;
			this.userName = userName;
		}

		
		public String getUserName() {
			return userName;
		}

		public String getMessage() {
			return message;
		}

		public String getMessageTime() {
			return messageTime;
		}
	
	}
	
	
	
	

	private class InputListener extends Observable implements KeyListener{
		
		private void sendMessage(){
			String message = inputMessage.getText();
			
			if( message.compareTo("") != 0 && message.compareTo("\n") != 0 ){
				inputMessage.setText("");
				
				String messageTime = formattedTime.format(new Date());
				
				setChanged();
				notifyObservers( new MessageInfo(user.getUserName(), message, messageTime) );
			}
		}
		
		@Override
		public void keyReleased(KeyEvent e) {
			if( e.getKeyCode() == 10 ){
				sendMessage();
			}
		}
		
		@Override
		public void keyPressed(KeyEvent e) {
		}
		
		@Override
		public void keyTyped(KeyEvent e) {
		}
	}
}
